﻿using WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ValidBox4Mvc;

namespace WebApp.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View(new UserInfo { Email = "123456@qq.com", Name = "小陈" });
        }

        /// <summary>
        /// 远程验证用户的名称
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="name">名称</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckName(int id, string name)
        {
            var dataBase = new List<KeyValuePair<int, string>>
            {
                new KeyValuePair<int,string >(1,"小陈"),
                new KeyValuePair<int,string >(2,"小张"),
                new KeyValuePair<int,string >(3,"小李"),
            };

            var exists = dataBase.Where(item => item.Key != id && item.Value == name).Count() > 0;
            if (exists)
            {
                return Json(new { state = false, message = "此名称已存在，请更换" });
            }
            return Json(new { state = true, message = string.Empty });
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="model">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(UserInfo model)
        {
            if (this.ModelState.IsValid == false)
            {
                var msg = this.ModelState.FirstModelError().ErrorMessage;
                return Content(msg);
            }

            return Content("保存用户信息成功");
        }
    }
}
